﻿using TradePublish.Common;
using log4net;
using TradePublish.Service;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Reflection;
using System.Threading;
using TradePublish.Entity;
using TradePublish.Service;
using System.Data.OracleClient;
namespace TradePublish.Dao
{
    public class ApplyUserContractDao
    {
        private ILog log = null;

        public ApplyUserContractDao()
        {
            this.log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        }

        
        /// <summary>
        /// 一个申请人，调用一次。
        /// </summary>
        /// <param name="results"></param> 
        public void saveContract(List<ApplyUserContract> results)
        {
            if ((results != null) && (results.Count != 0))
            {
                while(true){
                    if (DateTime.Now.Hour == 6 && DateTime.Now.Minute < 30  || (DateTime.Now.Hour >=8 && DateTime.Now.Hour <18  &&  Convert.ToInt32(DateTime.Now.DayOfWeek) !=0 && Convert.ToInt32(DateTime.Now.DayOfWeek) !=6   ) )
                    {
                        Thread.Sleep(180000);//3fenzhong 
                        continue;
                    }
                    break;
                }

                //先查出来以前的数据，看看是否业务员已经设置为无效了。
                DataSet dsOld = null;
                #region  读取
                while (true)
                {
                    DatabaseHelper dbh = new DatabaseHelper();
                    try
                    {
                        string cmdText = "select * from  APPLY_USER_CONTRACT where APPLY_USER_NAME ='" + results[0].applyUserName.Replace("'","''")+"'";
                        //OracleParameter applyUserNameP = new OracleParameter(":app", OracleType.NVarChar); 
                        //applyUserNameP.Value = results[0].applyUserName;
                        log.Debug("<<<<<<<" + cmdText + "【】" + results[0].applyUserName);
                         
                      //  dbh.AddParameter(applyUserNameP);
                        dsOld = dbh.ExecuteDataSet(cmdText ); 
                        break;
                    }
                    catch (Exception exception)
                    { 
                        this.log.Error("读取APPLY_USER_CONTRACT获得该申请人已采集信息时,发生异常.", exception);
                    }
                    finally
                    {
                        dbh.Dispose();
                    }
                    Thread.Sleep(0x3e8);
                }
                #endregion
                log.Debug("去掉错误和已存在的！！");
                #region 去掉错误的和已经存在的。
                if (dsOld != null && dsOld.Tables != null && dsOld.Tables.Count > 0 && dsOld.Tables[0].Rows != null && dsOld.Tables[0].Rows.Count > 0)
                {
                    for (int i = 0; i < results.Count;i++ )
                    {
                        ApplyUserContract row = results[i];
                        if (row.email != null && !row.email.Trim().Equals(""))
                        {
                            bool shouldDel = false;
                            for (int j = 0; j < dsOld.Tables[0].Rows.Count; j++)
                            {
                                String emailO = dsOld.Tables[0].Rows[j]["EMAIL"] == null ? "" : dsOld.Tables[0].Rows[j]["EMAIL"].ToString();
                                if (!emailO.Trim().Equals(""))
                                {
                                    if (emailO.Trim().Equals(row.email.Trim()))
                                    {
                                        shouldDel = true; //相同了，不需要插入
                                        break;
                                    } 
                                }
                            }
                            if (shouldDel)
                            {
                                results.RemoveAt(i);
                                i--;
                                if (results.Count == 0)
                                {
                                    break;
                                }
                            }
                        } 
                    }
                }
                #endregion
 
                while (true)
                {
                    DatabaseHelper dbh = new DatabaseHelper();
                    try
                    { 
                        dbh.BeginTransaction();
                        for (int i = 0; i < results.Count; i++)
                        {
                            string cmdText = "INSERT INTO  APPLY_USER_CONTRACT  (id,APPLY_USER_NAME,EMAIL,EMAIL_SOURCE_HTML,TELEPHONE,TELEPHONE_SOURCE_HTML,WANGWANG_NO,WANGWANG_SOURCE_HTML,IS_CHENGXINTONG,OFFICAL_WEBSITE,HAVE_OFFICE_WEBSITE,HAVE_EMAIL,HAVE_TELEPHONE,HAVE_WANGWANG )";
                            string str2 = cmdText;
                            cmdText = str2 + " VALUES (gen_sequence.nextval,'" + results[i].applyUserName.Replace("'", "''") +
                                "','" + results[i].email.Replace("'", "''") +
                                "','" + results[i].emailSourceHtml.Replace("'", "''") +
                                "','" + results[i].telephone.Replace("'", "''") +
                                "','" + results[i].telephoneSourceHtml.Replace("'", "''") +
                                "','" + results[i].wangwangNo.Replace("'", "''") +
                                "','" + results[i].wangwangHtml.Replace("'", "''") +
                                "'," + ((results[i].isChengxintong == null || results[i].isChengxintong.Equals("")) ? "0" : results[i].isChengxintong) +
                                ",'"+results[i].officalWebsite.Replace("'", "''") +"',"+results[i].haveOfficeWebsite+","+results[i].haveEmail+","+results[i].haveTelephone+","+results[i].haveWangwang
                                +")";
                            this.log.Debug("<<<<<<<<<<<<<<" + cmdText);
                            dbh.ExecuteNonQuery(cmdText,TradePublish.Service.ConnectionState.KeepOpen);
                        }
                        dbh.CommitTransaction();
                        break;
                    }
                    catch (Exception exception)
                    {
                        dbh.RollbackTransaction();  
                        this.log.Error("存入APPLY_USER_CONTRACT时,发生异常.", exception);
                        
                    }
                    finally
                    {
                        dbh.Dispose();
                    }
                    Thread.Sleep(0x3e8);
                } 
            }
        }
    }
}

